package com.yc.sole.common.handler;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONException;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
import com.yc.sole.common.dto.ProductAttributeDto;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * @author yizuomin
 * @date 2024/3/5 12:05
 **/
public class ProductAttributeTypeHandler extends JacksonTypeHandler {


    public ProductAttributeTypeHandler(Class<?> type) {
        super(type);
    }

    @Override
    protected List<ProductAttributeDto> parse(String json) {
        List<ProductAttributeDto> jsons = new ArrayList<>();
        try {
            List<ProductAttributeDto> productAttributeDtoList = JSONUtil.toList(json, ProductAttributeDto.class);
            if (CollUtil.isNotEmpty(productAttributeDtoList)) {
                jsons = productAttributeDtoList.stream().sorted(Comparator.comparing(ProductAttributeDto::getSort)).toList();
            }
        } catch (JSONException e) {
            jsons.add(JSONUtil.toBean(json, ProductAttributeDto.class));
        }
        return jsons;
    }
}
